package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.Dishes;
import com.etoak.entity.vo.DishesVO;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author et2406
 * @since 2024-11-18
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Override
    public void addDishes(Dishes dishes) {
        if (ObjectUtils.isNotEmpty((this.getByName(dishes.getName())))) {
            throw new CustomException("菜品名称重复");
        }
        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);

    }

    @Override
    public PageVO<DishesVO> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum,pageSize);
        List<DishesVO> list = baseMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(list);
        return new PageVO<>(pageInfo.getPageNum()
                ,pageInfo.getPageSize()
                ,list
                ,pageInfo.getTotal());
    }

    @Override
    public void update(int id, Dishes dishes) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw  new CustomException("菜品不存在");
        }
        String name = dishes.getName();
        if(StringUtils.isNotEmpty(name)){
            Dishes byName = this.getByName(name);
            if(ObjectUtils.isNotEmpty(byName)&&!byName.getId().equals(id)){
                throw new CustomException("已经有同名菜品");
            }
        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);

    }

    @Override
    public void delete(int id) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw  new CustomException("菜品不存在");
        }
        this.removeById(id);
    }

    @Override
    public boolean inIngredientsUsed(int ingredientId) {
        return lambdaQuery().eq(Dishes::getMain, ingredientId).or()
                .eq(Dishes::getMinor, ingredientId).or()
                .eq(Dishes::getSeasoning, ingredientId)
                .count()>0;
    }

    private Dishes getByName(String name) {
        return lambdaQuery().eq(Dishes::getName, name).one();
    }
}
